<?php
/**
 * 预约管理
 * 州弟医院信息系统 - 州弟学安全
 */

// 包含函数文件
require_once '../includes/functions.php';

// 检查用户是否已登录并具有管理员权限
if (!isLoggedIn() || !hasRole('admin')) {
    $_SESSION['error_msg'] = '您无权访问该页面';
    redirect('../login.php');
}

// 处理预约操作
$success = '';
$error = '';

// 处理删除预约请求
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $appointment_id = (int)$_GET['delete'];
    
    // 删除预约
    $sql = "DELETE FROM appointments WHERE id = $appointment_id";
    
    if ($conn->query($sql)) {
        // 记录操作日志
        logAction($_SESSION['user_id'], '删除预约（ID：' . $appointment_id . '）');
        
        $success = '预约删除成功！';
    } else {
        $error = '删除预约失败：' . $conn->error;
    }
}

// 处理预约状态更新请求
if (isset($_GET['status']) && is_numeric($_GET['id'])) {
    $appointment_id = (int)$_GET['id'];
    $status = $conn->real_escape_string($_GET['status']);
    
    $valid_statuses = ['待确认', '已确认', '已取消', '已完成', '未到诊'];
    
    if (in_array($status, $valid_statuses)) {
        $sql = "UPDATE appointments SET status = '$status' WHERE id = $appointment_id";
        
        if ($conn->query($sql)) {
            // 记录操作日志
            logAction($_SESSION['user_id'], '更新预约状态（ID：' . $appointment_id . '，状态：' . $status . '）');
            
            $success = '预约状态更新成功！';
        } else {
            $error = '更新预约状态失败：' . $conn->error;
        }
    } else {
        $error = '无效的预约状态';
    }
}

// 处理添加/编辑预约表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_appointment']) || isset($_POST['edit_appointment'])) {
        $patient_id = isset($_POST['patient_id']) ? (int)$_POST['patient_id'] : 0;
        $doctor_id = isset($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : 0;
        $department_id = isset($_POST['department_id']) ? (int)$_POST['department_id'] : 0;
        $appointment_date = $_POST['appointment_date'] ?? '';
        $appointment_time = $_POST['appointment_time'] ?? '';
        $reason = $_POST['reason'] ?? '';
        $status = $_POST['status'] ?? '待确认';
        $notes = $_POST['notes'] ?? '';
        $appointment_id = isset($_POST['appointment_id']) ? (int)$_POST['appointment_id'] : 0;
        
        // 基本验证
        if (empty($patient_id) || empty($doctor_id) || empty($department_id) || empty($appointment_date) || empty($appointment_time)) {
            $error = '请填写所有必填字段';
        } else {
            // 处理表单数据
            $patient_id = $conn->real_escape_string($patient_id);
            $doctor_id = $conn->real_escape_string($doctor_id);
            $department_id = $conn->real_escape_string($department_id);
            $appointment_date = $conn->real_escape_string($appointment_date);
            $appointment_time = $conn->real_escape_string($appointment_time);
            $reason = $conn->real_escape_string($reason);
            $status = $conn->real_escape_string($status);
            $notes = $conn->real_escape_string($notes);
            
            // 添加新预约
            if (isset($_POST['add_appointment'])) {
                $sql = "INSERT INTO appointments (patient_id, doctor_id, department_id, appointment_date, appointment_time, 
                        reason, status, notes, created_at) 
                        VALUES ('$patient_id', '$doctor_id', '$department_id', '$appointment_date', '$appointment_time', 
                        '$reason', '$status', '$notes', NOW())";
                
                if ($conn->query($sql)) {
                    $new_appointment_id = $conn->insert_id;
                    
                    // 记录操作日志
                    logAction($_SESSION['user_id'], '添加预约（ID：' . $new_appointment_id . '）');
                    
                    $success = '预约添加成功！';
                } else {
                    $error = '添加预约失败：' . $conn->error;
                }
            }
            // 编辑现有预约
            else {
                $sql = "UPDATE appointments SET patient_id = '$patient_id', doctor_id = '$doctor_id', department_id = '$department_id', 
                        appointment_date = '$appointment_date', appointment_time = '$appointment_time', reason = '$reason', 
                        status = '$status', notes = '$notes', updated_at = NOW() 
                        WHERE id = $appointment_id";
                
                if ($conn->query($sql)) {
                    // 记录操作日志
                    logAction($_SESSION['user_id'], '更新预约（ID：' . $appointment_id . '）');
                    
                    $success = '预约更新成功！';
                } else {
                    $error = '更新预约失败：' . $conn->error;
                }
            }
        }
    }
}

// 筛选条件
$filters = [];
$where_clauses = [];
$where_params = [];

// 日期筛选
$date_filter = $_GET['date'] ?? date('Y-m-d');
if (!empty($date_filter)) {
    $where_clauses[] = "a.appointment_date = ?";
    $where_params[] = $date_filter;
    $filters['date'] = $date_filter;
} else {
    $filters['date'] = '';
}

// 状态筛选
$status_filter = $_GET['status_filter'] ?? '';
if (!empty($status_filter)) {
    $where_clauses[] = "a.status = ?";
    $where_params[] = $status_filter;
    $filters['status'] = $status_filter;
} else {
    $filters['status'] = '';
}

// 医生筛选
$doctor_filter = isset($_GET['doctor']) ? (int)$_GET['doctor'] : 0;
if ($doctor_filter > 0) {
    $where_clauses[] = "a.doctor_id = ?";
    $where_params[] = $doctor_filter;
    $filters['doctor'] = $doctor_filter;
} else {
    $filters['doctor'] = 0;
}

// 科室筛选
$department_filter = isset($_GET['department']) ? (int)$_GET['department'] : 0;
if ($department_filter > 0) {
    $where_clauses[] = "a.department_id = ?";
    $where_params[] = $department_filter;
    $filters['department'] = $department_filter;
} else {
    $filters['department'] = 0;
}

// 构建查询语句
$sql = "SELECT a.*, p.name as patient_name, d.name as doctor_name, dp.name as department_name 
        FROM appointments a
        LEFT JOIN patients p ON a.patient_id = p.id
        LEFT JOIN doctors d ON a.doctor_id = d.id
        LEFT JOIN departments dp ON a.department_id = dp.id";

if (!empty($where_clauses)) {
    $sql .= " WHERE " . implode(' AND ', $where_clauses);
}

$sql .= " ORDER BY a.appointment_date ASC, a.appointment_time ASC";

// 执行查询
$appointments = [];
$stmt = $conn->prepare($sql);

if (!empty($where_params)) {
    $types = str_repeat('s', count($where_params));
    $stmt->bind_param($types, ...$where_params);
}

$stmt->execute();
$result = $stmt->get_result();

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $appointments[] = $row;
    }
}

// 如果是编辑请求，获取预约信息
$edit_appointment = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $appointment_id = (int)$_GET['edit'];
    $sql = "SELECT * FROM appointments WHERE id = $appointment_id";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $edit_appointment = $result->fetch_assoc();
    }
}

// 获取所有患者、医生和科室（用于下拉选择）
$patients = [];
$sql = "SELECT id, name FROM patients ORDER BY name";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $patients[] = $row;
    }
}

$doctors = [];
$sql = "SELECT id, name, department_id FROM doctors ORDER BY name";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $doctors[] = $row;
    }
}

$departments = [];
$sql = "SELECT id, name FROM departments ORDER BY name";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $departments[] = $row;
    }
}

// 预约状态列表
$statuses = ['待确认', '已确认', '已取消', '已完成', '未到诊'];

?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>预约管理 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="/assets\css/bootstrap_69c9e605.min.css">
    <link rel="stylesheet" href="/assets\css/all_3b858821.min.css">
    <link rel="stylesheet" href="/assets\css/style.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 px-0 admin-sidebar">
                <div class="py-3 px-3 bg-dark">
                    <a href="<?php echo SITE_URL; ?>admin/" class="text-white text-decoration-none">
                        <i class="fas fa-hospital-alt mr-2"></i>管理后台
                    </a>
                </div>
                <div class="p-3">
                    <div class="text-white mb-3">
                        <i class="fas fa-user-circle mr-1"></i> <?php echo $_SESSION['username']; ?>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/">
                                <i class="fas fa-tachometer-alt mr-2"></i>仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/users.php">
                                <i class="fas fa-users mr-2"></i>用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/patients.php">
                                <i class="fas fa-user-injured mr-2"></i>患者管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/doctors.php">
                                <i class="fas fa-user-md mr-2"></i>医生管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/departments.php">
                                <i class="fas fa-hospital mr-2"></i>科室管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="<?php echo SITE_URL; ?>admin/appointments.php">
                                <i class="fas fa-calendar-check mr-2"></i>预约管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/medicines.php">
                                <i class="fas fa-pills mr-2"></i>药品管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/records.php">
                                <i class="fas fa-notes-medical mr-2"></i>病历管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/logs.php">
                                <i class="fas fa-history mr-2"></i>系统日志
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/settings.php">
                                <i class="fas fa-cog mr-2"></i>系统设置
                            </a>
                        </li>
                        <li class="nav-item mt-3">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>">
                                <i class="fas fa-home mr-2"></i>返回前台
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>logout.php">
                                <i class="fas fa-sign-out-alt mr-2"></i>退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
            
            <!-- 主内容区 -->
            <div class="col-md-10 ml-sm-auto px-4 py-3">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">预约管理</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#addAppointmentModal">
                            <i class="fas fa-plus mr-1"></i> 添加预约
                        </button>
                    </div>
                </div>
                
                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <?php echo $success; ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <?php echo $error; ?>
                    </div>
                <?php endif; ?>
                
                <!-- 筛选工具栏 -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form method="get" class="row">
                            <div class="col-md-3 mb-2">
                                <label for="date">日期</label>
                                <input type="date" class="form-control" id="date" name="date" value="<?php echo $filters['date']; ?>">
                            </div>
                            <div class="col-md-3 mb-2">
                                <label for="status_filter">状态</label>
                                <select class="form-control" id="status_filter" name="status_filter">
                                    <option value="">所有状态</option>
                                    <?php foreach ($statuses as $status): ?>
                                        <option value="<?php echo $status; ?>" <?php echo $filters['status'] == $status ? 'selected' : ''; ?>>
                                            <?php echo $status; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3 mb-2">
                                <label for="doctor">医生</label>
                                <select class="form-control" id="doctor" name="doctor">
                                    <option value="0">所有医生</option>
                                    <?php foreach ($doctors as $doctor): ?>
                                        <option value="<?php echo $doctor['id']; ?>" <?php echo $filters['doctor'] == $doctor['id'] ? 'selected' : ''; ?>>
                                            <?php echo $doctor['name']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3 mb-2">
                                <label for="department">科室</label>
                                <select class="form-control" id="department" name="department">
                                    <option value="0">所有科室</option>
                                    <?php foreach ($departments as $department): ?>
                                        <option value="<?php echo $department['id']; ?>" <?php echo $filters['department'] == $department['id'] ? 'selected' : ''; ?>>
                                            <?php echo $department['name']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-12 mt-2 text-right">
                                <a href="appointments.php" class="btn btn-outline-secondary mr-2">重置</a>
                                <button type="submit" class="btn btn-primary">筛选</button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- 预约列表 -->
                <div class="card">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col">
                                <h5 class="mb-0">
                                    预约列表
                                    <?php if ($filters['date']): ?>
                                        - <?php echo date('Y年m月d日', strtotime($filters['date'])); ?>
                                    <?php endif; ?>
                                </h5>
                            </div>
                            <div class="col-auto">
                                <div class="btn-group">
                                    <a href="?date=<?php echo date('Y-m-d', strtotime('-1 day', strtotime($filters['date'] ?: date('Y-m-d')))); ?>" class="btn btn-sm btn-outline-secondary">
                                        <i class="fas fa-chevron-left"></i>
                                    </a>
                                    <a href="?date=<?php echo date('Y-m-d'); ?>" class="btn btn-sm btn-outline-primary">今天</a>
                                    <a href="?date=<?php echo date('Y-m-d', strtotime('+1 day', strtotime($filters['date'] ?: date('Y-m-d')))); ?>" class="btn btn-sm btn-outline-secondary">
                                        <i class="fas fa-chevron-right"></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>患者姓名</th>
                                        <th>医生姓名</th>
                                        <th>科室</th>
                                        <th>预约日期</th>
                                        <th>预约时间</th>
                                        <th>预约原因</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($appointments)): ?>
                                        <tr>
                                            <td colspan="9" class="text-center">暂无预约记录</td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($appointments as $appointment): ?>
                                            <tr>
                                                <td><?php echo $appointment['id']; ?></td>
                                                <td><?php echo $appointment['patient_name']; ?></td>
                                                <td><?php echo $appointment['doctor_name']; ?></td>
                                                <td><?php echo $appointment['department_name']; ?></td>
                                                <td><?php echo date('Y-m-d', strtotime($appointment['appointment_date'])); ?></td>
                                                <td><?php echo $appointment['appointment_time']; ?></td>
                                                <td><?php echo mb_substr($appointment['reason'], 0, 20) . (mb_strlen($appointment['reason']) > 20 ? '...' : ''); ?></td>
                                                <td>
                                                    <?php
                                                    $status_class = '';
                                                    switch ($appointment['status']) {
                                                        case '待确认':
                                                            $status_class = 'badge-warning';
                                                            break;
                                                        case '已确认':
                                                            $status_class = 'badge-success';
                                                            break;
                                                        case '已取消':
                                                            $status_class = 'badge-danger';
                                                            break;
                                                        case '已完成':
                                                            $status_class = 'badge-primary';
                                                            break;
                                                        case '未到诊':
                                                            $status_class = 'badge-secondary';
                                                            break;
                                                        default:
                                                            $status_class = 'badge-info';
                                                    }
                                                    ?>
                                                    <span class="badge <?php echo $status_class; ?>"><?php echo $appointment['status']; ?></span>
                                                </td>
                                                <td>
                                                    <div class="btn-group">
                                                        <button type="button" class="btn btn-sm btn-info dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                            更改状态
                                                        </button>
                                                        <div class="dropdown-menu">
                                                            <?php foreach ($statuses as $status): ?>
                                                                <?php if ($status != $appointment['status']): ?>
                                                                    <a class="dropdown-item" href="?id=<?php echo $appointment['id']; ?>&status=<?php echo $status; ?>&date=<?php echo $filters['date']; ?>">
                                                                        标记为：<?php echo $status; ?>
                                                                    </a>
                                                                <?php endif; ?>
                                                            <?php endforeach; ?>
                                                        </div>
                                                    </div>
                                                    <a href="?edit=<?php echo $appointment['id']; ?>" class="btn btn-sm btn-warning ml-1" title="编辑">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <a href="?delete=<?php echo $appointment['id']; ?>" class="btn btn-sm btn-danger ml-1" title="删除" onclick="return confirm('确定要删除此预约吗？此操作不可恢复！');">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="card-footer">
                        <div class="row align-items-center">
                            <div class="col">
                                <small class="text-muted">共 <?php echo count($appointments); ?> 条预约记录</small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 版权信息 -->
                <footer class="mt-5 text-center text-muted">
                    <p>
                        &copy; <?php echo date('Y'); ?> <?php echo SITE_NAME; ?>. 版权所有
                        <br>
                        <small>Powered by <a href="#" class="text-muted">州弟学安全</a> | 版本 <?php echo VERSION; ?></small>
                    </p>
                </footer>
            </div>
        </div>
    </div>
    
    <!-- 添加预约模态框 -->
    <div class="modal fade" id="addAppointmentModal" tabindex="-1" role="dialog" aria-labelledby="addAppointmentModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addAppointmentModalLabel">添加预约</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="patient_id">患者 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="patient_id" name="patient_id" required>
                                        <option value="">请选择患者</option>
                                        <?php foreach ($patients as $patient): ?>
                                            <option value="<?php echo $patient['id']; ?>"><?php echo $patient['name']; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="department_id">科室 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="department_id" name="department_id" required>
                                        <option value="">请选择科室</option>
                                        <?php foreach ($departments as $department): ?>
                                            <option value="<?php echo $department['id']; ?>"><?php echo $department['name']; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="doctor_id">医生 <span class="text-danger">*</span></label>
                            <select class="form-control" id="doctor_id" name="doctor_id" required>
                                <option value="">请先选择科室</option>
                            </select>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="appointment_date">预约日期 <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="appointment_date" name="appointment_date" value="<?php echo date('Y-m-d'); ?>" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="appointment_time">预约时间 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="appointment_time" name="appointment_time" required>
                                        <option value="">请选择时间</option>
                                        <option value="08:00">08:00</option>
                                        <option value="08:30">08:30</option>
                                        <option value="09:00">09:00</option>
                                        <option value="09:30">09:30</option>
                                        <option value="10:00">10:00</option>
                                        <option value="10:30">10:30</option>
                                        <option value="11:00">11:00</option>
                                        <option value="11:30">11:30</option>
                                        <option value="14:00">14:00</option>
                                        <option value="14:30">14:30</option>
                                        <option value="15:00">15:00</option>
                                        <option value="15:30">15:30</option>
                                        <option value="16:00">16:00</option>
                                        <option value="16:30">16:30</option>
                                        <option value="17:00">17:00</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="reason">预约原因 <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="reason" name="reason" rows="3" required></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="status">状态</label>
                                    <select class="form-control" id="status" name="status">
                                        <?php foreach ($statuses as $status): ?>
                                            <option value="<?php echo $status; ?>" <?php echo $status == '待确认' ? 'selected' : ''; ?>>
                                                <?php echo $status; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="notes">备注</label>
                                    <textarea class="form-control" id="notes" name="notes" rows="1"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="submit" name="add_appointment" class="btn btn-primary">添加</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 编辑预约模态框 -->
    <?php if ($edit_appointment): ?>
    <div class="modal fade" id="editAppointmentModal" tabindex="-1" role="dialog" aria-labelledby="editAppointmentModalLabel" aria-hidden="true" data-show="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editAppointmentModalLabel">编辑预约</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <input type="hidden" name="appointment_id" value="<?php echo $edit_appointment['id']; ?>">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_patient_id">患者 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="edit_patient_id" name="patient_id" required>
                                        <option value="">请选择患者</option>
                                        <?php foreach ($patients as $patient): ?>
                                            <option value="<?php echo $patient['id']; ?>" <?php echo $edit_appointment['patient_id'] == $patient['id'] ? 'selected' : ''; ?>>
                                                <?php echo $patient['name']; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_department_id">科室 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="edit_department_id" name="department_id" required>
                                        <option value="">请选择科室</option>
                                        <?php foreach ($departments as $department): ?>
                                            <option value="<?php echo $department['id']; ?>" <?php echo $edit_appointment['department_id'] == $department['id'] ? 'selected' : ''; ?>>
                                                <?php echo $department['name']; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="edit_doctor_id">医生 <span class="text-danger">*</span></label>
                            <select class="form-control" id="edit_doctor_id" name="doctor_id" required>
                                <option value="">请选择医生</option>
                                <?php foreach ($doctors as $doctor): ?>
                                    <option value="<?php echo $doctor['id']; ?>" data-department="<?php echo $doctor['department_id']; ?>" <?php echo $edit_appointment['doctor_id'] == $doctor['id'] ? 'selected' : ''; ?>>
                                        <?php echo $doctor['name']; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_appointment_date">预约日期 <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="edit_appointment_date" name="appointment_date" value="<?php echo date('Y-m-d', strtotime($edit_appointment['appointment_date'])); ?>" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_appointment_time">预约时间 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="edit_appointment_time" name="appointment_time" required>
                                        <option value="">请选择时间</option>
                                        <option value="08:00" <?php echo $edit_appointment['appointment_time'] == '08:00' ? 'selected' : ''; ?>>08:00</option>
                                        <option value="08:30" <?php echo $edit_appointment['appointment_time'] == '08:30' ? 'selected' : ''; ?>>08:30</option>
                                        <option value="09:00" <?php echo $edit_appointment['appointment_time'] == '09:00' ? 'selected' : ''; ?>>09:00</option>
                                        <option value="09:30" <?php echo $edit_appointment['appointment_time'] == '09:30' ? 'selected' : ''; ?>>09:30</option>
                                        <option value="10:00" <?php echo $edit_appointment['appointment_time'] == '10:00' ? 'selected' : ''; ?>>10:00</option>
                                        <option value="10:30" <?php echo $edit_appointment['appointment_time'] == '10:30' ? 'selected' : ''; ?>>10:30</option>
                                        <option value="11:00" <?php echo $edit_appointment['appointment_time'] == '11:00' ? 'selected' : ''; ?>>11:00</option>
                                        <option value="11:30" <?php echo $edit_appointment['appointment_time'] == '11:30' ? 'selected' : ''; ?>>11:30</option>
                                        <option value="14:00" <?php echo $edit_appointment['appointment_time'] == '14:00' ? 'selected' : ''; ?>>14:00</option>
                                        <option value="14:30" <?php echo $edit_appointment['appointment_time'] == '14:30' ? 'selected' : ''; ?>>14:30</option>
                                        <option value="15:00" <?php echo $edit_appointment['appointment_time'] == '15:00' ? 'selected' : ''; ?>>15:00</option>
                                        <option value="15:30" <?php echo $edit_appointment['appointment_time'] == '15:30' ? 'selected' : ''; ?>>15:30</option>
                                        <option value="16:00" <?php echo $edit_appointment['appointment_time'] == '16:00' ? 'selected' : ''; ?>>16:00</option>
                                        <option value="16:30" <?php echo $edit_appointment['appointment_time'] == '16:30' ? 'selected' : ''; ?>>16:30</option>
                                        <option value="17:00" <?php echo $edit_appointment['appointment_time'] == '17:00' ? 'selected' : ''; ?>>17:00</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="edit_reason">预约原因 <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="edit_reason" name="reason" rows="3" required><?php echo $edit_appointment['reason']; ?></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_status">状态</label>
                                    <select class="form-control" id="edit_status" name="status">
                                        <?php foreach ($statuses as $status): ?>
                                            <option value="<?php echo $status; ?>" <?php echo $edit_appointment['status'] == $status ? 'selected' : ''; ?>>
                                                <?php echo $status; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_notes">备注</label>
                                    <textarea class="form-control" id="edit_notes" name="notes" rows="1"><?php echo $edit_appointment['notes']; ?></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="submit" name="edit_appointment" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>
        $(document).ready(function() {
            $('#editAppointmentModal').modal('show');
        });
    </script>
    <?php endif; ?>

    <script src="/assets\js/jquery-3_7b53a2dc.5.1.min.js"></script></script></script></script>
    <script src="/assets\js/popper_9c21e708.min.js"></script></script></script></script>
    <script src="/assets\js/bootstrap_a618e9ff.min.js"></script></script></script></script>
    <script src="/assets\js/main.js"></script></script>
    <script>
        $(document).ready(function(){
            // 科室选择后，更新对应医生列表
            function updateDoctors(departmentId, doctorSelect) {
                doctorSelect.find('option').not(':first').remove();
                
                if (departmentId) {
                    var doctors = <?php echo json_encode($doctors); ?>;
                    var count = 0;
                    
                    for (var i = 0; i < doctors.length; i++) {
                        if (doctors[i].department_id == departmentId) {
                            doctorSelect.append('<option value="' + doctors[i].id + '">' + doctors[i].name + '</option>');
                            count++;
                        }
                    }
                    
                    if (count === 0) {
                        doctorSelect.html('<option value="">该科室暂无医生</option>');
                    } else {
                        doctorSelect.find('option:first').text('请选择医生');
                    }
                } else {
                    doctorSelect.html('<option value="">请先选择科室</option>');
                }
            }
            
            // 科室选择变化事件 - 添加
            $('#department_id').change(function() {
                var departmentId = $(this).val();
                updateDoctors(departmentId, $('#doctor_id'));
            });
            
            // 科室选择变化事件 - 编辑
            $('#edit_department_id').change(function() {
                var departmentId = $(this).val();
                updateDoctors(departmentId, $('#edit_doctor_id'));
            });
            
            // 初始加载编辑表单中的医生列表
            if ($('#edit_department_id').length) {
                var departmentId = $('#edit_department_id').val();
                if (departmentId) {
                    updateDoctors(departmentId, $('#edit_doctor_id'));
                    $('#edit_doctor_id').val('<?php echo $edit_appointment['doctor_id'] ?? ''; ?>');
                }
            }
        });
    </script>
</body>
</html> 